package com.example.demo.controller;

import com.example.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    private static Map<String, Student> students= new HashMap<>();

    static {
        Student s1=new Student("1","Tony");
        students.put(s1.getId(),s1);
        Student s2=new Student("2","Jerry");
        students.put(s2.getId(),s2);
    }

    @RequestMapping("list")
    public String list(ModelMap map){
        map.put("studentList",students.values());
        return "list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        students.remove(id);
        return "redirect:/list";
    }

    @RequestMapping("create")
    public String create(){
        return "create";
    }

    @RequestMapping("save")
    public String save(Student s) {
        if (s.getId() == null) {
            s.setid(String.valueOf(students.size() + 1));
        }
        students.put(s.getId(),s);
        return "redirect:/list";
    }

    @RequestMapping("update/{id}")
    public String update(@PathVariable String id,ModelMap map) {
        Student s = students.get(id);
        map.put("student",s);
        return "update";
    }

}
